<?php

/*
  Copyright (c) 2010 Samuel Stevens

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

 */
if (!defined('INDEX')) {
    exit("This script cannot be called directly");
}

class AutoDB {

    private static $known_primarykeys = array();
    private static $staticDB;

    static function SetDB(Database $newDB) {
        self::$staticDB = $newDB;
    }

    static function GetDB() {
        return self::$staticDB;
    }

    private $db;
    private $table;
    private $pk;
    private $recordClass = "AutoDBRecord";
    private $cols = "";
    private $where = "";
    private $order = "";
    private $limit = "";
    private $join = "";

    function AutoDB($table, $primarykey=False) {
        $this->db = self::$staticDB;
        $this->table = $table;

        if ($primarykey !== False)
            $this->pk = $primarykey;
        else if (!isset(self::$known_primarykeys[$table])) {
            $result = $this->db->query("Show Columns From `$table` Where `Key` = 'PRI'");
            if ($result == False)
                throw new DatabaseException("Table does not exist or has no primary key");

            self::$known_primarykeys[$table] = $this->pk = $result['Field'];
        }
        else
            $this->pk = $this->known_primarykeys[$table];
    }

    function SetRecordClass($class) {
        if (!is_string($class) || !is_subclass_of($class, "AutoDBRecord"))
            return False;
        $this->recordClass = $class;
        return True;
    }

    function TableName() {
        return $this->table;
    }

    function PrimaryKey() {
        return $this->pk;
    }

    function LastError() {
        return $this->db->get_last_error();
    }

    function Create($fields=array()) {
        return new $this->recordClass($fields, $this);
    }

    private function _AddBackTicks($name) {
        if (stripos($name, ".") === False)
            $name = ($name == '*') ? '*' : "`$name`";
        else {
            $parts = explode(".", $name);
            foreach ($parts as $id => $part)
                $parts[$id] = ($part == '*') ? '*' : "`$part`";
            $name = implode(".", $parts);
        }
        return $name;
    }

    function Select($column, $backticks=True) {
        if (is_array($column)) {
            foreach ($column as $c)
                $this->Select($c, $backticks);
            return $this;
        }
        if (stripos($column, ',') !== False) {
            foreach (explode(',', $column) as $c)
                $this->Select(trim($c), $backticks);
            return $this;
        }
        //Function calls sum(table.col) etc..
        if ($backticks &&
                preg_match('/([a-zA-Z0-9_-]+)\(((?:[a-zA-Z0-9_-]+\.)?[a-zA-Z0-9_\-\*]+)\)(.*)/', $column, $matches)) {
            $column = $matches[1] . "(" . $this->_AddBackTicks($matches[2]) . ")" . $matches[3];
        }
        if (!empty($this->cols))
            $this->cols .= ", ";
        //table.col as colAlias
        $asPos = stripos($column, ' as ');
        if ($asPos !== False && $backticks) {
            $column = explode(substr($column, $asPos, 4), $column);
            if (strpos($column[0], '(') === False) //Don't backtick functions
                $left = $this->_AddBackTicks($column[0]);
            else
                $left = $column[0];

            $right = $this->_AddBackTicks($column[1]);

            $this->cols .= $left . ' as ' . $right;
        }
        else
            $this->cols .= ($backticks) ? $this->_AddBackTicks($column) : $column;
        return $this;
    }

    function OrWhere($field, $value) {
        return $this->Where($field, $value, True, "Or");
    }

    function Where($field, $value=False, $backticks=True, $joiner="And") {
        if ($field === false || $field === null) {
            return $this;
        }
        if (is_array($field)) {
            foreach ($field as $f => $v)
                $this->Where($f, $v, $backticks, $joiner);
            return $this;
        }

        $value = db_escape($value);
        $value = (is_numeric($value)) ? $value : "'$value'";

        if (!empty($this->where))
            $this->where .= " $joiner ";
        $comparison = " =";
        if (substr_count($field, '>') > 0 ||
                substr_count($field, '<') > 0 ||
                substr_count($field, '=') > 0) {
            //If the field ends in a comparison ie 'ID >'
            //(Would the field be more than 1 word?)
            $wordcount = str_word_count($field, 0, "><=!");
            $words = explode(" ", $field);

            //Get the comparison operator
            $comparison = " " . $words[$wordcount - 1];
            //Remove the comparison from the field and glue back together
            unset($words[$wordcount - 1]);
            $field = implode(" ", $words);
        }
        $field = ($backticks) ? $this->_AddBackTicks($field) : $field;
        $this->where .= "$field$comparison $value";
        return $this;
    }

    function OrLike($field, $value) {
        return $this->Like($field, $value, False, "Or");
    }

    function NotLike($field, $value) {
        return $this->Like($field, $value, True);
    }

    function OrNotLike($field, $value) {
        return $this->Like($field, $value, True, "Or");
    }

    function Like($field, $value=false, $not=False, $joiner="And") {
        if ($field === false || $field === null) {
            return $this;
        }
        if (is_array($field)) {
            foreach ($field as $f => $v)
                $this->Like($f, $v, $not, $joiner);
            return $this;
        }
        if (!empty($this->where))
            $this->where .= " $joiner ";
        $not = ($not) ? " Not" : "";
        $value = db_escape($value);
        $field = $this->_AddBackTicks($field);
        $this->where .= "$field$not Like '$value'";
        return $this;
    }

    function OrderBy($order) {
        if (!empty($this->order))
            $this->order .= ", ";
        $order = db_escape($order);
        $this->order .= "$order";
        return $this;
    }

    function Limit($rows, $offset="") {
        $rows = db_escape($rows);
        $offset = db_escape($offset);
        $this->limit = "Limit $rows";
        if (!empty($offset))
            $this->limit .= ", $offset";
        return $this;
    }

    function JoinOn($table, $column1, $column2, $type="", $backticks=True) {
        return $this->Join($table, "$this->table.$column1 = $table.$column2", $type, $backticks);
    }

    function Join($table, $on, $type="", $backticks=True) {
        //$this->join = '';
        if (!empty($type))
            $this->join .= ucwords($type) . ' ';

        //add backticks to 'table1.col = table2.col' only
        if ($backticks &&
                preg_match('/((?:[a-zA-Z0-9_-]+\.)?[a-zA-Z0-9_\-\*]+) ?= ?((?:[a-zA-Z0-9_-]+\.)?[a-zA-Z0-9_\-\*]+)/', $on, $matches)) {
            $left = $this->_AddBackTicks(trim($matches[1]));
            $right = $this->_AddBackTicks(trim($matches[2]));
            $on = $left . ' = ' . $right;
        }
        if ($backticks)
            $table = $this->_AddBackTicks($table);
        $this->join .= " Join $table On $on ";
        return $this;
    }

    function GenerateQuery($reset=True) {
        $query = "Select ";
        if (!empty($this->cols))
            $query .= $this->cols;
        else
            $query .= "*";
        $query .= " From `$this->table`";
        if (!empty($this->join))
            $query .= " " . $this->join;
        if (!empty($this->where))
            $query .= " Where $this->where";
        if (!empty($this->order))
            $query .= " Order By $this->order";
        if (!empty($this->limit))
            $query .= " " . $this->limit;
        if ($reset)
            $this->Reset();
        return $query;
    }

    function Run(&$theQuery=Null) {
        $theQuery = $this->GenerateQuery();
        return $this->Query($theQuery);
    }

    function Reset() {
        $this->cols = "";
        $this->where = "";
        $this->order = "";
        $this->limit = "";
        $this->join = "";
    }

    function Query($query, $getResults = true) {
        $result = $this->db->query($query, True, False);
        if ($result == False)
            return False;
        elseif ($getResults) {
            $records = array();
            foreach ($result as $fields)
                $records[] = new $this->recordClass($fields, $this);
            return new AutoDBResultSet($records);
        } else {
            return true;
        }
    }

    function GetFirst() {
        $result = $this->Run();
        if ($result != False)
            return $result->First();
        return $result;
    }

    function Get($id=False) {
        if ($id == False)
            return $this->Run();
        if (is_numeric($id)) {
            $result = $this->GetWhere("`$this->pk` = $id");
            if ($result == False)
                return False;
            return $result[0];
        }
        else
            return False;
    }

    function GetWhere($where, $order="") {
        if (!empty($order) && !stripos($order, "Order By"))
            $order = "Order By $order";
        $result = $this->db->query("Select * From `$this->table` Where $where $order", True, False);
        if ($result == False)
            return False;
        $records = array();
        foreach ($result as $fields)
            $records[] = new $this->recordClass($fields, $this);
        return new AutoDBResultSet($records);
    }

    function Delete($id) {
        $result = $this->Get($id);
        if (is_a($result, $this->recordClass)) {
            return $result->Delete();
        }
        return False;
    }

}

?>